﻿#region Usings

using FluentValidation;
using Yandex.Market.Api.Model;

#endregion

namespace Yandex.Market.Api.Validation
{
    internal class CurrencyValidator : AbstractValidator<Currency>
    {
        public CurrencyValidator()
        {
            RuleFor(currency => currency.ID).NotEmpty().WithMessage("Код валюты обязательно.");
            RuleFor(currency => currency.Rate).Must(IsRateValid).WithMessage(
                                                                             "Неверное значение курса валюты к курсу основной валюты, взятой за единицу (валюта, для которой rate=\"1\")");
// ReSharper disable PossibleInvalidOperationException
            RuleFor(currency => currency.Plus.Value).Must(plus => plus < 31).When(currency => currency.Plus.HasValue);
// ReSharper restore PossibleInvalidOperationException
        }

        private static bool IsRateValid(string rate)
        {
            bool valid;
            switch (rate)
            {
                case Currency.CB:
                    valid = true;
                    break;
                case Currency.CBRF:
                    valid = true;
                    break;
                case Currency.NBK:
                    valid = true;
                    break;
                case Currency.NBU:
                    valid = true;
                    break;
                default:
                    double result;
                    valid = double.TryParse(rate, out result);
                    break;
            }
            return valid;
        }
    }
}